package ma.co.cdm.esign.messaging;

import java.util.HashSet;
import java.util.Set;

import flex.messaging.MessageClient;
import flex.messaging.MessageClientListener;
import flex.messaging.messages.CommandMessage;
import flex.messaging.messages.Message;
import flex.messaging.services.messaging.adapters.ActionScriptAdapter;

public class FlexMessagingAdapter extends ActionScriptAdapter implements MessageClientListener
{

	private Set<String> clientIds = new HashSet<String>();

	private static FlexMessagingAdapter messageAdapter;

	public static FlexMessagingAdapter getInstance()
	{
		return messageAdapter;
	}

//	public void sendDocNotification(Document document)
//	{
//
//		if(clientIds != null && clientIds.size() > 0)
//		{
//			Message msg = new AsyncMessageExt();
//	       	msg.setMessageId(UUIDUtils.createUUID());
//	        msg.setTimestamp(new Date().getTime());
//	        msg.setBody(document);
//	        msg.setDestination("pushed-data");
//	        msg.setTimeToLive(0);
//	        MessageService msgService = (MessageService) getDestination().getService();
//	        msgService.pushMessageToClients(msg, false);
//		}
//	}
	public FlexMessagingAdapter() {
		super();
		MessageClient.addMessageClientCreatedListener(this);
		if(messageAdapter == null && messageAdapter != this)
		{
			messageAdapter = this;
		}
	}
	 @Override public Object invoke(Message message)
	{
		System.out.println("Receive message");

		return super.invoke(message);
	}
	public void messageClientCreated(MessageClient messageClient) {
		// Add the adapter as MessageClient destroyed listener, so it can get
        // destruction notifications as the MessageClient gets destroyed due to
        // Consumer unsubscribe, disconnect, or session invalidation.
        messageClient.addMessageClientDestroyedListener(this);

	}
	public void messageClientDestroyed(MessageClient messageClient) {
        String clientId = (String)messageClient.getClientId();
        clientIds.remove(clientId);
	}

	 @Override public Object manage(CommandMessage commandMessage)
	    {
	        int operation = commandMessage.getOperation();
	        String clientId = (String)commandMessage.getClientId();
	        switch (operation)
	        {
	            case CommandMessage.SUBSCRIBE_OPERATION:
	                clientIds.add(clientId);
	                break;
	            case CommandMessage.UNSUBSCRIBE_OPERATION:
	                clientIds.remove(clientId);
	                break;
	            default:
	                break;
	        }

	        return super.manage(commandMessage);
	    }

	    /**
	     * Return true, so manage method gets called as Consumer subscribes.
	     */
	    public boolean handlesSubscriptions()
	    {
	        return true;
	    }
}
